package com.dmai.capacity.platform.log.model;

import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.github.structlog4j.IToLog;
import com.google.common.collect.Maps;

import cn.hutool.extra.spring.SpringUtil;
import lombok.Builder;
import lombok.Data;
import org.apache.commons.lang3.time.DateUtils;

/**
 * 业务日志
 */
@Data
@Builder
public class Log implements IToLog {


    private String appName;
    private String serverIP;
    private String serverPort;
    private String clientIp;
    private String timestamp;

    private String objectId;
    private String objectType;

    private Date requestTime;
    private String requestParams;

    private Map<String, String> objectParam;
    private String msg;

    private String traceId;
    private String spanId;
    private String sql;

    private String responseCode;
    private String responseData;


    private String userId;
    private String userName;
    private String clientId;
    private String operation;

    @Override
    public Object[] toLog() {
        return new Object[]{
//                "appName",     Optional.ofNullable(SpringUtil.getProperty("spring.application.name")).orElse(""),
//                "serverIP",    Optional.ofNullable(SpringUtil.getProperty("spring.cloud.client.ip-address")).orElse(""),
//                "serverPort",  Optional.ofNullable(SpringUtil.getProperty("server.port")).orElse(""),
                "traceId", Optional.ofNullable(traceId).orElse(""),
                "clientIp", Optional.ofNullable(clientIp).orElse(""),

//                "spanId" , Optional.ofNullable(spanId).orElse("")    ,
//                "timestamp" ,  Optional.ofNullable(timestamp).orElse("")  ,
//                "objectId" , Optional.ofNullable(objectId).orElse("")    ,
                "requestTime", Optional.ofNullable(DateUtil.format(requestTime,"yyyy-MM-dd HH:mm:ss.SSS")).orElse(""),
                "requestParams", Optional.ofNullable(requestParams).orElse(""),
                "responseCode", Optional.ofNullable(responseCode).orElse(""),
                "responseData", Optional.ofNullable(responseData).orElse(""),
//                "objectType" , Optional.ofNullable(objectType).orElse("")    ,
                "objectParam", this.objectParam(),
//                "sql" ,Optional.ofNullable(sql).orElse("")    ,
//                "msg" , Optional.ofNullable(msg).orElse("")


        };
    }


    private String objectParam() {
        return Optional.ofNullable(objectParam).orElse(Maps.newHashMap()).keySet().stream().map(key -> String.format("%s=%s", key, objectParam.get(key))).sorted().collect(Collectors.joining("&", "", ""));
    }

}